package com.topjia.music.user.file.impl;

import com.google.common.io.Files;
import com.obs.services.ObsClient;
import com.obs.services.model.ObjectMetadata;
import com.topjia.music.user.file.FileClient;
import com.topjia.music.user.file.config.FileClientProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.UUID;

@Slf4j
public class HwOBSFileClient implements FileClient {
    private ObsClient oss;
    private String bucketName;
    private String viewHost;

    public HwOBSFileClient(FileClientProperties fileClientProperties) {
        this.oss = new ObsClient(fileClientProperties.getAccessKey(), fileClientProperties.getSecretKey(), fileClientProperties.getEndPoint());
        this.bucketName = fileClientProperties.getBucketName();
        this.viewHost = fileClientProperties.getViewHost();
    }

    @Override
    public String upload(String bizType, String bizId, MultipartFile file) {
        String filePath = getFilePath(bizType, bizId, file.getOriginalFilename());
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            this.oss.putObject(this.bucketName, filePath, inputStream, objectMetadata);
        } catch (Exception e) {
            log.error("文件上传失败，原因：{}， {}", e.getMessage(), e);
            throw new SecurityException("文件上传失败！");
        } finally {
            try {
                if (Objects.nonNull(inputStream)) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return this.viewHost + filePath;
    }

    private String getFilePath(String bizType, String bizId, String originalFilename) {
        return Paths.get(bizType, bizId, getUUIDFileName(originalFilename)).toString().replaceAll("\\\\", "/");
    }

    private String getUUIDFileName(String originalFilename) {
        return UUID.randomUUID().toString().replaceAll("-", "") + "." + Files.getFileExtension(originalFilename);
    }
}
